package org.esti.security;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.esti.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;


/**
 * @author Artem Loginov (logart)
 */

@Component
@Aspect
public class Authentication {

    @Autowired
    @Qualifier("authenticationManager")
    private AuthenticationManager authenticationManager;

    @Pointcut("execution(* org.esti.controller.AuthController.dropAdminAccount(..))")
    public void adminLogin() {
    }

    @Pointcut("execution(* org.esti.controller.RegistrationController." +
            "getUserInfoFromRegistrationForm(String, org.esti.model.User, ..)) " +
            "&& args(str, user, ..)")
    public void registration(String str, User user) {
    }

    @After("adminLogin()")
    public void adminAutoLogin() {
        authenticate("admin", "445566");
    }

    @After("registration(password, user)")
    public void autoLogin(String password, User user) {
        authenticate(user.getLogin(), password);
    }


    private void authenticate(String username, String password) {
        try {
            UsernamePasswordAuthenticationToken usernameAndPassword =
                    new UsernamePasswordAuthenticationToken(
                            username, password);
            org.springframework.security.core.Authentication auth = authenticationManager.authenticate(usernameAndPassword);

            // Place the new Authentication object in the security context.
            SecurityContextHolder.getContext().setAuthentication(auth);

        } catch (AuthenticationException e) {
            SecurityContextHolder.getContext().setAuthentication(null);
        }
    }
}
